<template>
  <div class="personal-center">

<div class="floating-menu">
      <div class="menu-item" @click="scrollToSection('account-management')">
        <i class="el-icon-user-solid"></i>
        <span>账户管理</span>
      </div>
      <div class="menu-item" @click="scrollToSection('notification-settings')">
        <i class="el-icon-bell"></i>
        <span>通知设置</span>
      </div>
      <div class="menu-item" @click="scrollToSection('feedback')">
        <i class="el-icon-chat-dot-round"></i>
        <span>反馈处理</span>
      </div>
      <div class="menu-item danger" @click="scrollToSection('cancel-account')">
        <i class="el-icon-warning"></i>
        <span>注销处理</span>
      </div>
      <div class="menu-main" @click="toggleMenu">
        <i class="el-icon-more"></i>
      </div>
      </div>

    <!-- 用户信息卡片 -->
    <div class="user-card">
      <div class="user-info-section">
        <el-avatar :size="80" :src="userInfo.avatar"></el-avatar>
        <div class="user-details">
          <h3>{{ userStore.username }}</h3>
        </div>
        <div class="action-buttons">
        <!-- 美化后的按钮 -->
        <el-button type="primary" class="custom-button" @click="goToCommunity">
          <i class="el-icon-edit"></i>
          <span>去发帖</span>
        </el-button>
        
        <el-button type="success" class="custom-button" @click="goToCollect">
          <i class="el-icon-star-on"></i>
          <span>我的收藏</span>
        </el-button>
      </div>
      </div>
    </div>

    <!-- 账户管理 -->
<div id="account-management" class="section-card">
  <h2 class="section-title">账户管理</h2>
  
  <!-- 修改资料 -->
  <div class="edit-section">
    <div class="edit-form">
      <el-form :model="editForm" ref="editFormRef" label-width="100px" :rules="editRules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="editForm.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="editForm.gender" placeholder="请选择性别">
                <el-option label="男" value="male"></el-option>
                <el-option label="女" value="female"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学校" prop="school">
              <el-input v-model="editForm.school" placeholder="请输入当前学校"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标院校" prop="targetSchool">
              <el-input v-model="editForm.targetSchool" placeholder="请输入目标院校"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="考试年份" prop="examYear">
              <el-date-picker
                v-model="editForm.examYear"
                type="year"
                value-format="YYYY"
                format="YYYY年"
                placeholder="选择考试年份"
                @change="handleYearChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="http://localhost:8081/userpro/uploadAvatar"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="uploadHeaders">
                <img 
                  v-if="editForm.avatar" 
                  :src="editForm.avatar" 
                  class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                type="password" 
                v-model="editForm.newPassword" 
                placeholder="输入新密码（留空则不修改）"
                show-password></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                type="password" 
                v-model="editForm.confirmPassword" 
                placeholder="再次输入新密码"
                show-password></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="saveProfile" 
            :loading="saveLoading">
            {{ saveLoading ? '保存中...' : '保存修改' }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</div>

    <!-- 通知设置 -->
    <div id="notification-settings" class="section-card">
      <h2 class="section-title">通知设置</h2>
      
      <!-- 当前时间显示 -->
      <div class="current-time">
        <span>当前时间：{{ currentTime }}</span>
      </div>
      
      <div class="notification-card">
        <!-- 每日任务提醒 -->
        <div class="notification-item">
          <div class="notification-info">
            <h4>每日任务提醒</h4>
            <p>提醒您完成每日学习任务</p>
            <p v-if="notificationSettings.dailyTask.enabled" class="next-reminder">
              设置时间: {{ notificationSettings.dailyTask.time }}
            </p>
            <p v-if="notificationSettings.dailyTask.enabled && notificationSettings.dailyTask.lastTriggered" class="last-reminder">
              上次提醒: {{ formatTime(notificationSettings.dailyTask.lastTriggered) }}
            </p>
          </div>
          <div class="notification-settings">
            <el-switch v-model="notificationSettings.dailyTask.enabled" active-color="#409EFF" @change="toggleDailyReminder"></el-switch>
            <el-time-picker
              v-model="notificationSettings.dailyTask.time"
              :disabled="!notificationSettings.dailyTask.enabled"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="选择时间"
              :picker-options="{ selectableRange: '00:00:00 - 23:59:59' }"
              @change="updateReminderTime('dailyTask')"
            >
            </el-time-picker>
          </div>
        </div>
        
        <!-- 帖子回复提醒 -->
        <div class="notification-item">
          <div class="notification-info">
            <h4>帖子回复提醒</h4>
            <p>当有人回复您的帖子时提醒</p>
            <p v-if="notificationSettings.postReply.enabled" class="next-reminder">
              设置时间: {{ notificationSettings.postReply.time }}
            </p>
            <p v-if="notificationSettings.postReply.enabled && notificationSettings.postReply.lastTriggered" class="last-reminder">
              上次提醒: {{ formatTime(notificationSettings.postReply.lastTriggered) }}
            </p>
          </div>
          <div class="notification-settings">
            <el-switch v-model="notificationSettings.postReply.enabled" active-color="#409EFF" @change="togglePostReminder"></el-switch>
            <el-time-picker
              v-model="notificationSettings.postReply.time"
              :disabled="!notificationSettings.postReply.enabled"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="选择时间"
              :picker-options="{ selectableRange: '00:00:00 - 23:59:59' }"
              @change="updateReminderTime('postReply')"
            >
            </el-time-picker>
          </div>
        </div>
        
        <div class="save-settings">
          <el-button type="primary" @click="saveNotificationSettings">保存设置</el-button>
        </div>
      </div>
    </div>

    <!-- 反馈处理 -->
    <div id="feedback" class="section-card">
      <h2 class="section-title">反馈处理</h2>
      
      <div class="feedback-content">
        <!-- 提交反馈 -->
        <div class="feedback-form">
          <h3 class="sub-title">提交反馈</h3>
          <el-form :model="feedbackForm" label-width="80px" :rules="rules" ref="feedbackFormRef">
            <el-row :gutter="20">
              <el-col :span="12">
                <!-- 修改反馈类型选择框 -->
<el-form-item label="反馈类型" prop="feedbackType">
  <el-select v-model="feedbackForm.feedbackType" placeholder="请选择反馈类型">
    <el-option label="功能建议" value="suggestion"></el-option>
    <el-option label="问题反馈" value="question"></el-option>
    <el-option label="系统相关" value="system"></el-option>
    <el-option label="其他" value="other"></el-option>
  </el-select>
</el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="反馈标题" prop="title">
                  <el-input
                    v-model="feedbackForm.title"
                    placeholder="请输入反馈标题"
                    maxlength="100"
                    show-word-limit
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="反馈内容" prop="content">
              <el-input
                type="textarea"
                :rows="5"
                v-model="feedbackForm.content"
                placeholder="请详细描述您的反馈内容"
                maxlength="500"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button 
                type="primary" 
                @click="submitFeedback" 
                :loading="submitLoading"
              >
                {{ submitLoading ? '提交中...' : '提交反馈' }}
              </el-button>
              <el-button @click="resetFeedbackForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 历史反馈 -->
        <div class="feedback-history">
          <el-collapse v-model="historyCollapse">
            <el-collapse-item title="历史反馈" name="history">
              <template #title>
                <div class="history-header">
                  <span>历史反馈</span>
                  <el-button 
                    type="text" 
                    size="small" 
                    @click.stop="loadFeedbackHistory" 
                    :loading="historyLoading"
                  >
                    刷新
                  </el-button>
                </div>
              </template>
              <div class="history-list" v-loading="historyLoading">
                <div v-if="feedbackHistory.length === 0" class="empty-history">
                  <p>暂无反馈记录</p>
                </div>
                <div v-for="item in feedbackHistory" :key="item.feedbackId" class="history-item">
                  <div class="item-header">
                    <span class="type">{{ getTypeLabel(item.feedbackType) }}</span>
                    <span class="date">{{ formatDate(item.createdAt) }}</span>
                  </div>
                  <div class="history-title">{{ item.title }}</div>
                  <div class="history-content">{{ item.content }}</div>
                  <div class="history-status" :class="getStatusClass(item.status)">
                    {{ getStatusLabel(item.status) }}
                  </div>
                  <div v-if="item.adminReply && item.adminReply.trim()" class="admin-reply">
                    <div class="reply-label">管理员回复：</div>
                    <div class="reply-content">{{ item.adminReply }}</div>
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>

    <!-- 注销处理 -->
<div id="cancel-account" class="section-card danger-section">
  <h2 class="section-title danger-title">注销处理</h2>
  
  <div class="warning-box">
    <el-alert
      title="危险操作"
      type="error"
      description="注销账户将禁用您的账户，您将无法登录和使用平台功能，但数据会被保留。如需重新激活请联系管理员。"
      show-icon
      :closable="false"
    >
    </el-alert>
  </div>
  
  <div class="cancel-form">
    <el-form :model="cancelForm" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="注销原因">
            <el-select v-model="cancelForm.reason" placeholder="请选择注销原因">
              <el-option label="不再使用该平台" value="1"></el-option>
              <el-option label="找到了更好的平台" value="2"></el-option>
              <el-option label="隐私担忧" value="3"></el-option>
              <el-option label="其他原因" value="4"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <el-checkbox v-model="cancelForm.confirm">
              我理解并确认：注销账户后将无法正常使用平台功能
            </el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="详细说明">
        <el-input
          type="textarea"
          :rows="4"
          v-model="cancelForm.description"
          placeholder="请详细说明您的注销原因"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" :disabled="!cancelForm.confirm" @click="confirmCancel">
          确认注销账户
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</div>


    <!-- 提醒弹窗 -->
    <el-dialog
      :title="reminder.title"
      :visible.sync="showReminder"
      width="400px"
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <div class="reminder-content">
        <div class="reminder-icon">
          <i class="iconfont icon-bell" style="color: #409EFF; font-size: 48px;"></i>
        </div>
        <div class="reminder-message">{{ reminder.message }}</div>
        <div class="reminder-time">{{ reminder.time }}</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="snoozeReminder(5)">稍后提醒(5分钟)</el-button>
        <el-button type="primary" @click="dismissReminder">我知道了</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { useUserStore } from '@/store/user'
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'

export default {
  name: 'UnifiedProfile',
  components: {
    Loading
  },
  setup() {
    const userStore = useUserStore()
    
    onMounted(() => {
      userStore.initialize()
    })
    
    return {
      userStore
    }
  },
  data() {
  return {
    loading: false,
    saveLoading: false, // 添加保存按钮的loading状态
    userInfo: {
      id: null,
      username: '',
      realName: '',
      email: '',
      phone: '',
      gender: '',
      school: '',
      targetSchool: '',
      status: '',
      examYear: '',
      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      vipLevel: 3,
      points: 1280,
      
    },
    editForm: {
      id: null,
      username: '',
      email: '',
      phone: '',
      avatar: '',
      gender: '',
      school: '',
      targetSchool: '',
      examYear: '',
      newPassword: '',
      confirmPassword: ''
    },
    // 添加编辑表单的验证规则
    editRules: {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度应在2-20个字符之间', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      newPassword: [
        { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
      ],
      confirmPassword: [
        { 
          validator: (rule, value, callback) => {
            if (this.editForm.newPassword && value !== this.editForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ]
    },
    uploadHeaders: {
      'Authorization': localStorage.getItem('token') || ''
    },
    uploadAvatarUrl: 'http://localhost:8081/userpro/uploadAvatar',
    
    // 反馈相关
    feedbackForm: {
      feedbackType: '',
      title: '',
      content: ''
    },
    rules: {
      feedbackType: [
        { required: true, message: '请选择反馈类型', trigger: 'change' }
      ],
      title: [
        { required: true, message: '请输入反馈标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度应在2-100个字符之间', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入反馈内容', trigger: 'blur' },
        { min: 10, max: 500, message: '内容长度应在10-500个字符之间', trigger: 'blur' }
      ]
    },
    feedbackHistory: [],
    submitLoading: false,
    historyLoading: false,
    historyCollapse: [],
    baseURL: 'http://localhost:8081',
    
    // 通知设置
    notificationSettings: {
      dailyTask: {
        enabled: true,
        time: '09:00',
        lastTriggered: null,
        triggered: false
      },
      postReply: {
        enabled: true,
        time: '18:30',
        lastTriggered: null,
        triggered: false
      }
    },
    showReminder: false,
    reminder: {
      title: '',
      message: '',
      time: '',
      type: ''
    },
    currentTime: '',
    timeChecker: null,
    clockTimer: null,
    
    // 注销账户
    cancelForm: {
      reason: '',
      description: '',
      confirm: false
    }
  };
},
  created() {
    this.fetchUserInfo();
    this.loadFeedbackHistory();
    this.updateCurrentTime();
    this.startTimeChecker();
    this.loadSettings();
  },
  beforeDestroy() {
    this.stopTimeChecker();
  },
  methods: {
    // 获取当前用户ID - 修复关键方法
    getCurrentUserId() {
      // 优先级顺序：userStore.userId > userStore.user.id > localStorage
      let userId = null;
      
      if (this.userStore.userId) {
        userId = this.userStore.userId;
      } else if (this.userStore.user && this.userStore.user.id) {
        userId = this.userStore.user.id;
      } else if (this.userStore.user && this.userStore.user.userId) {
        userId = this.userStore.user.userId;
      } else {
        userId = localStorage.getItem('userId') || localStorage.getItem('user_id');
      }
      
      console.log('获取到的用户ID:', userId);
      return userId;
    },

    // 用户信息相关 - 修复获取用户信息方法
    async fetchUserInfo() {
      try {
        this.loading = true;
        const userId = this.getCurrentUserId();
        
        if (!userId) {
          console.error('无法获取用户ID');
          ElMessage.error('无法获取用户信息，请重新登录');
          return;
        }
        
        const response = await axios.get(`/api/user/find?id=${userId}`);
        console.log('正在获取用户信息，用户ID:', response.data.examYear);
        
        if (response.data) {
          // 确保ID正确设置
          this.userInfo = {
            ...this.userInfo,
            ...response.data,
            id: userId, // 确保ID正确设置
            username: response.data.username || this.userInfo.username,
            realName: response.data.realName || response.data.real_name || '',
            email: response.data.email || '',
            phone: response.data.phone || '',
            gender: response.data.gender || '',
            school: response.data.school || '',
            targetSchool: response.data.targetSchool || response.data.target_school || '',
            status: response.data.status !== undefined ? response.data.status : 'active',
            examYear: response.data.examYear
          };
          // 初始化编辑表单 - 确保ID正确传递
          this.editForm = {
            id: userId, // 使用获取到的userId
            username: this.userInfo.username,
            email: this.userInfo.email,
            phone: this.userInfo.phone,
            avatar: this.userInfo.avatar,
            gender: this.userInfo.gender,
            school: this.userInfo.school,
            targetSchool: this.userInfo.targetSchool,
            examYear: String(response.data.examYear), // 确保是整数
            newPassword: '',
            confirmPassword: ''
          };
          
          console.log('用户信息获取成功:', this.userInfo);
          console.log('编辑表单初始化:', this.editForm);
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        ElMessage.error('获取用户信息失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },




// 添加滚动到指定部分的方法
    scrollToSection(sectionId) {
      const element = document.getElementById(sectionId);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' });
      }
    },
    
    // 添加切换菜单显示状态的方法
    toggleMenu() {
      const menu = document.querySelector('.floating-menu');
      menu.classList.toggle('active');
    },
    
    // 原有的跳转方法
    goToCommunity() {
      this.$router.push('/community').catch(err => {
        console.error('跳转到社区页面失败:', err);
      });
    },
    
    goToCollect() {
      this.$router.push('/collect').catch(err => {
        console.error('跳转到收藏页面失败:', err);
      });
    },










    getGenderText(gender) {
      switch (gender) {
        case 'male':
        case '1':
        case 'M':
          return '男';
        case 'female':
        case '2':
        case 'F':
          return '女';
        default:
          return '未设置';
      }
    },

    getStatusText(status) {
      const statusStr = String(status).toLowerCase();
      switch (statusStr) {
        case 'active':
        case '1':
        case 'normal':
        case 'enabled':
        case 'true':
          return '正常';
        case 'inactive':
        case '0':
        case 'disabled':
        case 'false':
          return '未激活';
        case 'banned':
        case 'blocked':
        case '-1':
        case '2':
          return '已封禁';
        case 'pending':
        case '3':
          return '待审核';
        default:
          return status ? '正常' : '未设置';
      }
    },

    getStatusType(status) {
      const statusStr = String(status).toLowerCase();
      switch (statusStr) {
        case 'active':
        case '1':
        case 'normal':
        case 'enabled':
        case 'true':
          return 'success';
        case 'inactive':
        case '0':
        case 'disabled':
        case 'false':
          return 'warning';
        case 'banned':
        case 'blocked':
        case '-1':
        case '2':
          return 'danger';
        case 'pending':
        case '3':
          return 'info';
        default:
          return status ? 'success' : 'info';
      }
    },

    // 头像上传
    handleAvatarSuccess(response, file) {
      console.log(response,'2');
       if (response) {
        const avatarUrl =response.file;
        localStorage.setItem('userAvatar', avatarUrl)
        this.editForm.avatar = avatarUrl;
        this.userInfo.avatar = avatarUrl;
        this.userStore.setAvatar(avatarUrl);
        ElMessage.success('头像上传成功');
      } else {
        ElMessage.error('头像上传失败: ' + (response.message || '未知错误'));
      }
    },

    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        ElMessage.error('只能上传图片格式文件!');
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },

    // 处理年份变化
    handleYearChange(value) {
      // this.editForm.examYear = vva
      // // 确保年份是整数类型
      // if (value) {
      //   this.editForm.examYear = parseInt(value);
      // } else {
      //   this.editForm.examYear = null;
      // }
    },

    // 保存资料 - 修复保存方法
    async saveProfile() {
      // 表单验证
      if (!this.$refs.editFormRef) {
        ElMessage.error('表单验证失败');
        return;
      }

      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          ElMessage.error('请检查表单输入');
          return false;
        }

        // 检查用户ID
        if (!this.editForm.id) {
          ElMessage.error('用户ID不能为空');
          return;
        }
        
        this.saveLoading = true;
        
        try {
          const updateData = {
            userId: this.editForm.id,
            username: this.editForm.username,
            email: this.editForm.email,
            phone: this.editForm.phone,
            avatar: localStorage.getItem('userAvatar') || this.editForm.avatar,
            gender: this.editForm.gender,
            school: this.editForm.school,
            targetSchool: this.editForm.targetSchool,
            examYear: this.editForm.examYear ? parseInt(this.editForm.examYear) : null // 确保是整数
          };
          
          console.log('准备更新用户信息:', updateData);
          
          await axios.put('/userpro/updateProfile', updateData);
          
          if (this.editForm.newPassword) {
            await axios.put('/userpro/updatePassword', {
              userId: this.editForm.id,
              password: this.editForm.newPassword
            });
          }
          
          this.userStore.setUser({
            username: this.editForm.username,
            avatar: this.editForm.avatar
          });
          
          this.userInfo = { ...this.userInfo, ...updateData };
          this.editForm.newPassword = '';
          this.editForm.confirmPassword = '';
          
          ElMessage.success('个人信息更新成功');
        } catch (error) {
          console.error('更新个人信息失败:', error);
          ElMessage.error('更新个人信息失败: ' + (error.response?.data?.message || '未知错误'));
        } finally {
          this.saveLoading = false;
        }
      });
    },

    resetForm() {
      this.editForm = {
        id: this.userInfo.id,
        username: this.userInfo.username,
        email: this.userInfo.email,
        phone: this.userInfo.phone,
        avatar: this.userInfo.avatar,
        gender: this.userInfo.gender,
        school: this.userInfo.school,
        targetSchool: this.userInfo.targetSchool,
        examYear: this.userInfo.examYear ? parseInt(this.userInfo.examYear) : null, // 确保是整数
        newPassword: '',
        confirmPassword: ''
      };
      
      // 清除表单验证
      if (this.$refs.editFormRef) {
        this.$refs.editFormRef.clearValidate();
      }
      
      ElMessage.info('表单已重置');
    },

    // 反馈相关
    getUserId() {
      return this.getCurrentUserId() || '2';
    },

    async loadFeedbackHistory() {
  this.historyLoading = true;
  try {
    const userId = this.getUserId();
    const response = await axios.get(`${this.baseURL}/feedback/user/${userId}`);
    
    this.feedbackHistory = response.data;
    
    // 添加调试信息，帮助排查类型显示问题
    if (this.feedbackHistory.length > 0) {
      console.log('反馈历史数据示例:', this.feedbackHistory[0]);
      console.log('第一条数据的feedbackType:', this.feedbackHistory[0].feedbackType, '类型:', typeof this.feedbackHistory[0].feedbackType);
    }
    
  } catch (error) {
    console.error('加载反馈历史失败:', error);
    ElMessage.error('加载反馈历史失败');
  } finally {
    this.historyLoading = false;
  }
},

// 5. 改进 submitFeedback 方法，确保类型正确提交
async submitFeedback() {
  this.$refs.feedbackFormRef.validate(async (valid) => {
    if (!valid) return false;

    this.submitLoading = true;
    try {
      // 数字到枚举值的映射
      const typeMapping = {
        '1': 'suggestion',  // 功能建议
        '2': 'question',    // 问题反馈
        '3': 'system',      // 系统相关
        '4': 'other'        // 其他
      };
      
      const feedbackData = {
        userId: parseInt(this.getUserId()),
        username: this.userStore.username || '测试用户',
        // 如果选择的是数字，转换为枚举值；否则直接使用
        feedbackType: typeMapping[this.feedbackForm.feedbackType] || this.feedbackForm.feedbackType,
        title: this.feedbackForm.title.trim(),
        content: this.feedbackForm.content.trim()
      };

      console.log('提交的反馈数据:', feedbackData);

      await axios.post(`${this.baseURL}/feedback/insert`, feedbackData, {
        headers: { 'Content-Type': 'application/json' }
      });
      
      ElMessage.success('反馈提交成功，感谢您的建议！');
      this.resetFeedbackForm();
      await this.loadFeedbackHistory();
    } catch (error) {
      console.error('提交反馈失败:', error);
      ElMessage.error('提交反馈失败');
    } finally {
      this.submitLoading = false;
    }
  });
},

    resetFeedbackForm() {
      this.$refs.feedbackFormRef.resetFields();
      this.feedbackForm = {
        feedbackType: '',
        title: '',
        content: ''
      };
    },

   getTypeLabel(type) {
  const typeStr = String(type).toLowerCase();
  
  const types = {
    // 后端枚举值 -> 中文显示
    'question': '问题反馈',
    'system': '系统相关', 
    'suggestion': '功能建议',
    'other': '其他',
    
    // 兼容可能的数字格式（如果前端传的是数字）
    '1': '功能建议',    // suggestion
    '2': '问题反馈',    // question  
    '3': '系统相关',    // system
    '4': '其他',        // other
    1: '功能建议',
    2: '问题反馈', 
    3: '系统相关',
    4: '其他'
  };
  
  // 直接匹配
  if (types[type] !== undefined) {
    return types[type];
  }
  
  // 字符串匹配
  if (types[typeStr] !== undefined) {
    return types[typeStr];
  }
  
  console.warn('未识别的反馈类型:', type, '类型:', typeof type);
  return `未知类型(${type})`;
},

// 3. 修复 getStatusLabel 方法，根据后端枚举值映射
getStatusLabel(status) {
  const statusStr = String(status).toLowerCase();
  
  const statusLabels = {
    // 后端枚举值 -> 中文显示
    'pending': '待处理',
    'processing': '处理中',
    'resolved': '已解决',
    'rejected': '已拒绝',
    
    // 兼容可能的数字格式
    '0': '待处理',
    '1': '处理中', 
    '2': '已解决',
    '3': '已拒绝',
    0: '待处理',
    1: '处理中',
    2: '已解决', 
    3: '已拒绝'
  };
  
  if (statusLabels[status] !== undefined) {
    return statusLabels[status];
  }
  
  if (statusLabels[statusStr] !== undefined) {
    return statusLabels[statusStr];
  }
  
  console.warn('未识别的反馈状态:', status, '类型:', typeof status);
  return `未知状态(${status})`;
},

// 4. 修复 getStatusClass 方法
getStatusClass(status) {
  const statusStr = String(status).toLowerCase();
  
  const statusClasses = {
    // 后端枚举值 -> CSS类名
    'pending': 'pending',
    'processing': 'processing', 
    'resolved': 'resolved',
    'rejected': 'rejected',
    
    // 兼容数字格式
    '0': 'pending',
    '1': 'processing',
    '2': 'resolved', 
    '3': 'rejected',
    0: 'pending',
    1: 'processing',
    2: 'resolved',
    3: 'rejected'
  };
  
  if (statusClasses[status] !== undefined) {
    return statusClasses[status];
  }
  
  if (statusClasses[statusStr] !== undefined) {
    return statusClasses[statusStr];
  }
  
  return 'pending';
},

    formatDate(dateString) {
      if (!dateString) return '';
      try {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric', month: '2-digit', day: '2-digit',
          hour: '2-digit', minute: '2-digit'
        });
      } catch (error) {
        return dateString;
      }
    },

    // 通知设置相关
    updateCurrentTime() {
      const now = new Date();
      this.currentTime = now.toLocaleString('zh-CN', {
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit', second: '2-digit'
      });
    },

    startTimeChecker() {
      this.clockTimer = setInterval(() => {
        this.updateCurrentTime();
        this.checkReminders();
      }, 1000);
      this.checkReminders();
    },

    stopTimeChecker() {
      if (this.timeChecker) {
        clearInterval(this.timeChecker);
        this.timeChecker = null;
      }
      if (this.clockTimer) {
        clearInterval(this.clockTimer);
        this.clockTimer = null;
      }
    },

    checkReminders() {
      const now = new Date();
      const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
      const currentDate = now.toDateString();
      const currentSeconds = now.getSeconds();

      if (currentSeconds !== 0) return;

      // 检查每日任务提醒
      if (this.notificationSettings.dailyTask.enabled && 
          this.notificationSettings.dailyTask.time === currentTime) {
        const lastTriggeredDate = this.notificationSettings.dailyTask.lastTriggered ? 
          new Date(this.notificationSettings.dailyTask.lastTriggered).toDateString() : null;
        
        if (lastTriggeredDate !== currentDate) {
          this.showDailyTaskReminder();
          this.notificationSettings.dailyTask.lastTriggered = now.getTime();
          this.saveSettings();
        }
      }

      // 检查帖子回复提醒
      if (this.notificationSettings.postReply.enabled && 
          this.notificationSettings.postReply.time === currentTime) {
        const lastTriggeredDate = this.notificationSettings.postReply.lastTriggered ? 
          new Date(this.notificationSettings.postReply.lastTriggered).toDateString() : null;
        
        if (lastTriggeredDate !== currentDate) {
          this.showPostReplyReminder();
          this.notificationSettings.postReply.lastTriggered = now.getTime();
          this.saveSettings();
        }
      }
    },

    showDailyTaskReminder() {
      this.reminder = {
        title: '每日任务提醒',
        message: '您有每日学习任务待完成，请及时查看并完成今日任务！',
        time: `提醒时间：${new Date().toLocaleString('zh-CN')}`,
        type: 'dailyTask'
      };
      this.showReminder = true;
      this.playNotificationSound();
      this.showBrowserNotification('每日任务提醒', '您有每日学习任务待完成！');
    },

    showPostReplyReminder() {
      this.reminder = {
        title: '帖子回复提醒',
        message: '您的帖子有了新的回复，快去看看吧！',
        time: `提醒时间：${new Date().toLocaleString('zh-CN')}`,
        type: 'postReply'
      };
      this.showReminder = true;
      this.playNotificationSound();
      this.showBrowserNotification('帖子回复提醒', '您的帖子有了新的回复！');
    },

    playNotificationSound() {
      try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
        gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
        oscillator.start();
        oscillator.stop(audioContext.currentTime + 0.3);
      } catch (error) {
        console.log('无法播放提醒音效:', error);
      }
    },

    showBrowserNotification(title, message) {
      if ('Notification' in window) {
        if (Notification.permission === 'granted') {
          new Notification(title, { body: message, icon: '/favicon.ico' });
        } else if (Notification.permission !== 'denied') {
          Notification.requestPermission().then(permission => {
            if (permission === 'granted') {
              new Notification(title, { body: message, icon: '/favicon.ico' });
            }
          });
        }
      }
    },

    handleClose(done) {
      this.$confirm('确认关闭提醒？')
        .then(_ => { done(); })
        .catch(_ => {});
    },

    dismissReminder() {
      this.showReminder = false;
      this.$message.success('提醒已关闭');
    },

    snoozeReminder(minutes) {
      this.showReminder = false;
      setTimeout(() => {
        if (this.reminder.type === 'dailyTask') {
          this.showDailyTaskReminder();
        } else {
          this.showPostReplyReminder();
        }
      }, minutes * 60 * 1000);
      this.$message.success(`将在${minutes}分钟后再次提醒您`);
    },

    toggleDailyReminder(enabled) {
      if (!enabled) {
        this.notificationSettings.dailyTask.lastTriggered = null;
      }
      this.saveSettings();
      this.$message.success(enabled ? '每日任务提醒已开启' : '每日任务提醒已关闭');
    },

    togglePostReminder(enabled) {
      if (!enabled) {
        this.notificationSettings.postReply.lastTriggered = null;
      }
      this.saveSettings();
      this.$message.success(enabled ? '帖子回复提醒已开启' : '帖子回复提醒已关闭');
    },

    updateReminderTime(type) {
      this.notificationSettings[type].lastTriggered = null;
      this.saveSettings();
      this.$message.success('提醒时间已更新');
    },

    saveNotificationSettings() {
      this.$message.success('通知设置已保存');
      this.saveSettings();
    },

    saveSettings() {
      try {
        localStorage.setItem('notificationSettings', JSON.stringify(this.notificationSettings));
      } catch (error) {
        console.error('保存设置失败:', error);
      }
    },

    loadSettings() {
      try {
        const saved = localStorage.getItem('notificationSettings');
        if (saved) {
          const settings = JSON.parse(saved);
          this.notificationSettings = { ...this.notificationSettings, ...settings };
        }
      } catch (error) {
        console.error('加载设置失败:', error);
      }
    },

    formatTime(timestamp) {
      if (!timestamp) return '从未';
      return new Date(timestamp).toLocaleString('zh-CN');
    },

    goToCommunity() {
    this.$router.push('/community').catch(err => {
      console.error('跳转到社区页面失败:', err);
    });
  },

  goToCollect() {
    this.$router.push('/collect').catch(err => {
      console.error('跳转到收藏页面失败:', err);
    });
  },

  // 注销账户方法 - 修复注销功能
  async confirmCancel() {
    if (!this.cancelForm.reason) {
      this.$message.warning('请选择注销原因');
      return;
    }
    
    this.$confirm('确定要注销账户吗？注销后账户将被禁用，您将无法登录使用平台功能！', '警告', {
      confirmButtonText: '确认注销',
      cancelButtonText: '取消',
      type: 'error',
      center: true
    }).then(async () => {
      try {
        const userId = this.getCurrentUserId();
        
        if (!userId) {
          this.$message.error('无法获取用户ID，注销失败');
          return;
        }
        
        console.log('准备注销用户，用户ID:', userId);
        
        const response = await axios.put('/user/status', null, {
          params: { 
            userId: parseInt(userId),
            status: 0
          }
        });
        
        console.log('API响应:', response);
        
        if (response.status === 200) {
          this.$message({
            type: 'success',
            message: '账户已注销，您的账户已被禁用，3秒后自动跳转到登录页面'
          });
          
          if (this.userStore.logout) {
            this.userStore.logout();
          }
          localStorage.clear();
          sessionStorage.clear();
          
          let countdown = 3;
          const countdownInterval = setInterval(() => {
            countdown--;
            if (countdown > 0) {
              this.$message({
                type: 'success',
                message: `账户已注销，${countdown}秒后自动跳转到登录页面`
              });
            } else {
              clearInterval(countdownInterval);
              this.$router.push('/login').catch(() => {
                window.location.href = '/login';
              });
            }
          }, 1000);
        } else {
          this.$message.error('账户注销失败，请稍后重试');
        }
      } catch (error) {
        console.error('注销账户失败:', error);
        console.error('错误详情:', error.response);
        
        if (error.response && error.response.data) {
          this.$message.error('账户注销失败: ' + error.response.data);
        } else if (error.response && error.response.status === 404) {
          this.$message.error('接口不存在，请检查后端接口路径');
        } else {
          this.$message.error('账户注销失败，请检查网络连接');
        }
      }
    }).catch(() => {
      this.$message({ type: 'info', message: '已取消注销' });
    });
  },
  }
};
</script>

<style scoped>
.personal-center {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f5f7fa;
  min-height: 100vh;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.user-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.user-info-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-details {
  flex: 1;
  text-align: left;
}

.user-details h3 {
  margin: 0 0 5px 0;
  font-size: 18px;
}

.user-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.user-actions {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.section-card {
  background: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.danger-section {
  border: 1px solid #f56c6c;
  border-radius: 8px;
}

.section-title {
  color: #303133;
  margin: 0 0 25px 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  font-size: 18px;
  font-weight: 600;
}

.danger-title {
  color: #f56c6c;
}

.sub-title {
  color: #303133;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  font-size: 16px;
  font-weight: 500;
}

/* 账号管理样式 */
.edit-form {
  background: #fafbfc;
  padding: 20px;
  border-radius: 8px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 80px;
  height: 80px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  display: block;
}

/* 通知设置样式 */
.current-time {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 10px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  text-align: center;
  font-weight: 500;
  font-size: 16px;
}

.notification-card {
  background: #fafbfc;
  padding: 20px;
  border-radius: 8px;
}

.notification-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background: white;
  border-radius: 6px;
  margin-bottom: 15px;
}

.notification-item:last-child {
  margin-bottom: 0;
}

.notification-info {
  flex: 1;
}

.notification-info h4 {
  margin: 0 0 5px;
  font-size: 16px;
  color: #303133;
}

.notification-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.next-reminder {
  margin-top: 8px !important;
  font-size: 13px;
  color: #67c23a;
  background: #f0f9eb;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
}

.last-reminder {
  margin-top: 4px !important;
  font-size: 12px;
  color: #909399;
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
}

.notification-settings {
  display: flex;
  align-items: center;
  gap: 15px;
}

.save-settings {
  margin-top: 20px;
  text-align: center;
}

/* 反馈样式 */
.feedback-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.feedback-form {
  background: #fafbfc;
  padding: 20px;
  border-radius: 8px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.history-list {
  max-height: 400px;
  overflow-y: auto;
}

.empty-history {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.history-item {
  padding: 15px;
  background: white;
  border-radius: 6px;
  margin-bottom: 15px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
  border-left: 4px solid #409EFF;
  position: relative;
}

.item-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.item-header .type {
  background: #ecf5ff;
  color: #409EFF;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.item-header .date {
  color: #909399;
  font-size: 12px;
}

.history-title {
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
  font-size: 14px;
}

.history-content {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 10px;
}

.history-status {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.history-status.pending {
  background: #fdf6ec;
  color: #e6a23c;
}

.history-status.resolved {
  background: #f0f9eb;
  color: #67c23a;
}

.admin-reply {
  margin-top: 10px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid #67c23a;
}

.reply-label {
  font-size: 12px;
  color: #67c23a;
  margin-bottom: 5px;
  font-weight: bold;
}

.reply-content {
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

/* 注销账户样式 */
.warning-box {
  margin-bottom: 30px;
}

.cancel-form {
  background: #fafbfc;
  padding: 20px;
  border-radius: 8px;
}

.el-alert {
  border-radius: 8px;
}

/* 提醒弹窗样式 */
.reminder-content {
  text-align: center;
  padding: 20px;
}

.reminder-icon {
  margin-bottom: 20px;
}

.reminder-message {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 10px;
}

.reminder-time {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .personal-center {
    padding: 10px;
  }
  
  .user-card {
    padding: 15px;
  }
  
  .user-info-section {
    flex-direction: column;
    gap: 15px;
  }
  
  .user-details {
    text-align: center;
  }
  
  .user-actions {
    justify-content: center;
  }
  
  .user-actions {
    flex-direction: row;
    justify-content: center;
  }
  
  .section-card {
    padding: 15px;
  }
  
  .notification-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .notification-settings {
    width: 100%;
    justify-content: space-between;
  }
  
  .edit-form {
    padding: 15px;
  }

  
}
/* 悬浮菜单栏样式 */
.floating-menu {
  position: fixed;
  right: 30px;
  bottom: 30px;
  z-index: 1000;
  display: flex;
  flex-direction: column-reverse;
  align-items: flex-end;
  gap: 15px;
  transition: all 0.3s ease;
}

.floating-menu.active .menu-item {
  opacity: 1;
  transform: translateX(0);
  pointer-events: auto;
}

.menu-item {
  background: #409EFF;
  color: white;
  padding: 12px 20px;
  border-radius: 30px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  opacity: 0;
  transform: translateX(100px);
  transition: all 0.3s ease;
  pointer-events: none;
}

.menu-item.danger {
  background: #f56c6c;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.menu-item:hover {
  transform: translateX(-5px);
}

.menu-main {
  width: 56px;
  height: 56px;
  background: #409EFF;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  font-size: 20px;
  transition: all 0.3s ease;
  z-index: 1001;
}

.menu-main:hover {
  transform: rotate(90deg);
  background: #66b1ff;
}

/* 美化按钮样式 */
.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.custom-button {
  border-radius: 20px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.custom-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.custom-button i {
  font-size: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .floating-menu {
    right: 15px;
    bottom: 15px;
  }
  
  .menu-item {
    padding: 10px 16px;
    font-size: 14px;
  }
  
  .menu-main {
    width: 48px;
    height: 48px;
    font-size: 18px;
  }
  
  .action-buttons {
    flex-direction: column;
    width: 100%;
  }
  
  .custom-button {
    width: 100%;
    justify-content: center;
  }
}
</style>